package com.isesol.ime.validator.subscription;

import com.isesol.arch.fluentvalidator.*;
import com.isesol.ime.dal.mapper.*;
import com.isesol.ime.dal.model.*;
import com.isesol.ime.dal.model.dto.*;
import com.isesol.ime.enums.*;
import org.springframework.stereotype.*;

import javax.annotation.*;
import java.util.*;

@Component
public class SubscriptionBatchCopyValidator extends ValidatorHandler<SubscriptionDTO> implements Validator<SubscriptionDTO> {

	@Resource
	SubscriptionMapper subscriptionMapper;

	@Override
	public boolean validate(ValidatorContext context, SubscriptionDTO subscriptionDTO) {

		boolean result = true;

		List<SubscriptionDO> subscriptionList =
				subscriptionMapper.findByMachineIdAndStatus("", subscriptionDTO.getMachineId(), StatusEnum.ON.getStatus());

		/**
		 * 机床id（数据源校验）
		 */
		if (subscriptionList.isEmpty()) {

			context.addErrorMsg(ErrorCode.SOURCE_MACHINEID_ERROR.getMessage());
			result= false;
		}

		String[] machine = subscriptionDTO.getMachineIds().split(",");

		/**
		 * 机床id校验
		 */
		if (validateMachineIds(machine)) {

			context.addErrorMsg(ErrorCode.MACHINEID_REPEAT.getMessage());
			result= false;
		}

		return result;
	}

	public boolean validateMachineIds(String[] arry) {

		//用于判断是否有重复值的标记
		boolean flag = false;

		for (int i = 0; i < arry.length; i++) {
			String temp = arry[i];
			int count = 0;
			for (int j = 0; j < arry.length; j++) {
				String temp2 = arry[j];
				//有重复值就count+1
				if (temp.equals(temp2)) {
					count++;
				}
			}
			//由于中间又一次会跟自己本身比较所有这里要判断count>=2
			if (count >= 2) {
				flag = true;
			}
		}
		return flag;
	}

}